<?php

namespace app\modules\admin\controllers;

use app\constants\Code;
use app\extensions\XUtils;
use app\models\Article;
use yii;
use yii\data\Pagination;

/**
 * 用户组管理控制器
 * @author chenym
 * @since 2017.7.05
 * Class GroupController
 */
class ArticleController extends BaseController
{
    //分组状态
    public $artType = [
        1 => 'PHP',
        2 => 'GO',
    ];

    public function init()
    {
        parent::init();
    }

    public function beforeAction($action)
    {
        //$this->enableCsrfValidation = false;//前端自定义表单时，要关闭csrf验证，否则会找不到显示400 Bad Request
        return parent::beforeAction($action);
    }

    /**
     * 分组列表
     */
    public function actionIndex()
    {

        $page         = Yii::$app->request->get('page', 1);
        $articleModel = new Article();
        $condition    = $params    = [];
        $fields       = [
            'id',
            'title',
            'type_id',
            'status_is',
            'admin_id',
            'update_time',
        ];
        $adminList = $articleModel::find()->asArray()->where($condition)->orderBy('id')->offset(Code::ADMIN_PAGE_SIZE * ($page - 1))->limit(Code::ADMIN_PAGE_SIZE)->all();

        $total = $articleModel::find()->where($condition)->count();
        foreach ($adminList as $key => $value) {

            $adminList[$key]["type"]   = $this->artType[$value['type_id']];
            $adminList[$key]["status"] = $value['status_is'] ? "上线" : "下线";
        }

        $pages  = new Pagination(['totalCount' => $total, 'pageSize' => Code::ADMIN_PAGE_SIZE]);
        $assign = [
            'pages'    => $pages,
            'dataList' => $adminList,
        ];
        return $this->render('index', $assign);
    }

    /**
     * 添加or编辑分组
     */
    public function actionEdit()
    {
        $id       = intval(Yii::$app->request->get('id', 0));
        $artModel = new Article();
        $artModel->setScenario('update');
        //用户组所有数据

        $check = [];
        if ($id) {
            $check = $artModel::find()->asArray()->where(['id' => $id])->one();
            if (empty($check)) {
                XUtils::message("error", "文章不存在，请重试！", "/admin/article/index");
            }
        }

        
        if (Yii::$app->request->isPost) {
            $art               = Yii::$app->request->post('Art');
            $id                = Yii::$app->request->post('id');
            $data['title']     = $art['title'];
            $data['status_is'] = $art['status_is'];
            $data['content']   = $art['content'];

            $info = $artModel->find()->where(["title" => $data['title']])->one();

            if ($info && $id == 0) {
             $info &&   XUtils::message("error", "文章已存在，请重试！", ($id ? "/admin/article/edit?id={$id}" : "/admin/article/edit"));
            }

            if ($id) {
                $model = $artModel->findOne($id);
                //编辑文章
                $data['update_time'] = time();
                $data['admin_id']    = $this->adminId;
                $model->attributes   = $data;
                $affect              = $model->save();
            } else {
                //新增文章
                $data['create_time']  = $data['update_time']  = time();
                $data['admin_id']     = $this->adminId;
                $data['type_id']      = 1;
                $artModel->attributes = $data;
                $affect               = $artModel->save();
            }
            XUtils::message(($affect ? "success" : "error"), ($id ? "编辑" : "新增") . ($affect ? "成功" : "失败"), "/admin/article/index");
        }
        $assign = [
            'id'   => $id,
            'data' => $check,
        ];

        return $this->render('create', $assign);
    }

    /**
     * 删除文章
     */
    public function actionDelete()
    {
        $return = ["code" => 1001, "message" => "删除失败"];
        $id     = Yii::$app->request->post('id', 0);
        $model  = Article::findOne($id);
        if (empty($model)) {
            $return = ["code" => 1001, "message" => "文章不存在"];
        } else {
            $res                       = $model->delete();
            $res && $return["code"]    = "1000";
            $res && $return["message"] = "删除成功";
        }
        exit(XUtils::echoJson($return));
    }
}
